package com.qdxwx.web.controller.comment;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.article.ArticleService;
import com.qdxwx.data.service.book.BookService;
import com.qdxwx.data.service.comment.CommentService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.document.DocumentService;
import com.qdxwx.data.service.picture.PictureService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.article.Article;
import com.qdxwx.models.book.Book;
import com.qdxwx.models.comment.Comment;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.document.Document;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.picture.Picture;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 前台评论模块
 *
 * @author developer
 */
@Controller
@RequestMapping("/comment")
public class CommentController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);
    @Autowired
    private CommentService commentService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private WebsiteProfileService websiteProfileService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private BookService bookService;
    @Autowired
    private DocumentService documentService;
    @Autowired
    private PictureService pictureService;

    @RequestMapping("/add.html")
    public String addComment(HttpServletRequest request, ModelMap mmap) {
        int otherId = TKConvert.toInteger(request.getParameter("otherId"));
        int typeId = TKConvert.toInteger(request.getParameter("typeId"));
        String otherTitle;
        if (typeId == ModuleType.COURSE.ordinal()) {
            Course course = courseService.get(otherId);
            if (course == null) {
                return toErrorView(request, "找不到评论对像！");
            }
            otherTitle = course.getCourseName();
        } else if (typeId == ModuleType.BOOK.ordinal()) {
            Book book = bookService.get(otherId);
            if (book == null) {
                return toErrorView(request, "找不到评论对像！");
            }
            otherTitle = book.getTitle();
        } else if (typeId == ModuleType.ARTICLE.ordinal()) {
            Article article = articleService.get(otherId);
            if (article == null) {
                return toErrorView(request, "找不到评论对像！");
            }
            otherTitle = article.getTitle();
        } else if (typeId == ModuleType.DOCUMENT.ordinal()) {
            Document document = documentService.get(otherId);
            if (document == null) {
                return toErrorView(request, "找不到评论对像！");
            }
            otherTitle = document.getTitle();
        } else if (typeId == ModuleType.PICTURE.ordinal()) {
            Picture picture = pictureService.get(otherId);
            if (picture == null) {
                return toErrorView(request, "找不到评论对像！");
            }
            otherTitle = picture.getTitle();
        } else {
            return toErrorView(request, "参数错误！");
        }
        mmap.put("otherId", otherId);
        mmap.put("otherTitle", otherTitle);
        mmap.put("commentType", typeId);
        return getViewPath("comment/comment-add");
    }

    @RequestMapping("/reply.html")
    public String replyComment(HttpServletRequest request, ModelMap mmap) {
        int commentId = TKConvert.toInteger(request.getParameter("commentId"));
        Comment comment = commentService.get(commentId);
        if (comment == null) {
            return toErrorView(request, "找不到回复的评论对像！");
        }
        mmap.put("comment", comment);
        return getViewPath("comment/comment-reply");
    }

    /**
     * 添加评论
     */
    @PostMapping("/add.json")
    @ResponseBody
    public AjaxResult addComment(HttpServletRequest request) {
        long userId = LoginUser.getUserId(request);
        if (userId <=0 ) {
            return AjaxResult.auth("您未登录，请登录后再发表评论！");
        }
        int parentId = TKConvert.toInteger(request.getParameter("parentId"));
        int typeId = TKConvert.toInteger(request.getParameter("typeId"));
        int otherId = TKConvert.toInteger(request.getParameter("otherId"));
        String content = request.getParameter("content");
        if (TKString.isEmpty(content)) {
            return AjaxResult.error("请输入评论内容");
        }
        content = TKConvert.toURLDecode(content);
        if (content.length() < 5) {
            return AjaxResult.error("评论内容过于简单，请最少输入不少于5个字符的评论内容！");
        }
        if (content.length() > 800) {
            return AjaxResult.error("评论内容太长，评论内容不能多于800个字符！");
        }
        if (websiteProfileService.hasBadWord(content)) {
            return AjaxResult.error("内容包含了敏感词，请注意您的言行！");
        }
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setParentId(parentId);
        comment.setStatus(0);
        comment.setScore(TKConvert.toDouble(request.getParameter("score"),1.0));
        if (parentId > 0) {
            Comment parent = commentService.get(parentId);
            if (parent == null) {
                return AjaxResult.error("找不到对应的回复对像！");
            }
            comment.setTypeId(parent.getTypeId());
            comment.setOtherId(parent.getOtherId());
        } else {
            if (typeId < 1) return AjaxResult.error("评论类型错误");
            if (otherId < 1) return AjaxResult.error("评论关联id错误");
            //if (typeId == CommentType.COURSE.ordinal() || typeId == CommentType.COURSE_NODE.ordinal()) {
            //    if (!orderService.checkUserCoursePay(user.getUserId(), otherId)) {
            //        return AjaxResult.error("您还没有购买该课程,请购买后评论!");
            //    }
            //}
            if (typeId == ModuleType.COURSE.ordinal()) {
                Course course = courseService.get(otherId);
                if (course == null) {
                    return AjaxResult.error("找不到对应的评论对像！");
                }
            } else if (typeId == ModuleType.BOOK.ordinal()) {
                Book book = bookService.get(otherId);
                if (book == null) {
                    return AjaxResult.error("找不到对应的评论对像！");
                }
            } else if (typeId == ModuleType.ARTICLE.ordinal()) {
                Article article = articleService.get(otherId);
                if (article == null) {
                    return AjaxResult.error("找不到对应的评论对像！");
                }
            } else if (typeId == ModuleType.DOCUMENT.ordinal()) {
                Document document = documentService.get(otherId);
                if (document == null) {
                    return AjaxResult.error("找不到对应的评论对像！");
                }
            } else if (typeId == ModuleType.PICTURE.ordinal()) {
                Picture picture = pictureService.get(otherId);
                if (picture == null) {
                    return AjaxResult.error("找不到对应的评论对像！");
                }
            } else {
                return AjaxResult.error("参数错误！");
            }
            comment.setTypeId(typeId);
            comment.setOtherId(otherId);
        }
        Comment check = commentService.get(comment);
        if (check != null) {
            if (check.getAddTime().plusMinutes(10).isAfter(LocalDateTime.now())) {
                return AjaxResult.error("您刚已经提交了评论，请不要短时间对同一内容进行评论！");
            }
        }
        commentService.add(comment);
        return AjaxResult.success("发表评论成功！");
    }
}